<!--检测方案的关联物料产品操作组件-->
<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    width="800px"
    @close="handleClose"
    :close-on-click-modal="false"
  >
    <el-form 
      ref="formRef" 
      :model="localFormData" 
      :rules="rules" 
      label-width="120px"
      class="compact-form"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="物料编码" prop="material_code">
            <el-input 
              v-model="localFormData.material_code" 
              placeholder="请选择物料"
              readonly
              @click.native="showProductDialog"
              class="form-input"
            >
              <el-button 
                slot="append" 
                icon="el-icon-search"
                @click="showProductDialog"
              ></el-button>
            </el-input>
            <el-switch
              v-model="autoGenerateCode"
              inactive-text="自动生成"
              style="flex-shrink: 0"
              @change="handleAutoGenerateChange"
            ></el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物料名称" prop="material_name">
            <el-input 
              v-model="localFormData.material_name" 
              placeholder="请输入物料名称"
              class="form-input"
              @blur="checkNameUnique"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="规格型号" prop="material_sfn">
            <el-input 
              v-model="localFormData.material_sfn" 
              placeholder="请输入规格型号"
              class="form-input"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位" prop="unit">
            <el-input 
              v-model="localFormData.unit" 
              placeholder="请输入单位"
              class="form-input"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="最低检测数" prop="quantity_check_num">
            <el-input-number 
              v-model="localFormData.quantity_check_num" 
              :min="1"
              :controls="false"
              class="number-input"
              placeholder="请输入最低检测数"
            ></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最大不合格数" prop="quantity_unqualified_num">
            <el-input-number 
              v-model="localFormData.quantity_unqualified_num" 
              :min="0"
              :controls="false"
              class="number-input"
              placeholder="请输入最大不合格数"
            ></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20" class="defect-rate-row">
        <el-col :span="8">
          <el-form-item label="致命缺陷率(%)" prop="cr_rate">
            <el-input-number 
              v-model="localFormData.cr_rate" 
              :min="0"
              :max="100"
              :precision="2"
              class="rate-input"
              controls-position="right"
            ></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="严重缺陷率(%)" prop="maj_rate">
            <el-input-number 
              v-model="localFormData.maj_rate" 
              :min="0"
              :max="100"
              :precision="2"
              class="rate-input"
              controls-position="right"
            ></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="轻微缺陷率(%)" prop="min_rate">
            <el-input-number 
              v-model="localFormData.min_rate" 
              :min="0"
              :max="100"
              :precision="2"
              class="rate-input"
              controls-position="right"
            ></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="备注">
        <el-input
          v-model="localFormData.remark"
          type="textarea"
          :rows="2"
          placeholder="请输入备注"
          class="remark-input"
        ></el-input>
      </el-form-item>
    </el-form>

    <!-- 产品选择对话框 -->
    <el-dialog
      title="选择物料"
      :visible.sync="productDialogVisible"
      width="70%"
      append-to-body
    >
      <div class="filter-container">
        <el-input
          v-model="productQuery.keyword"
          placeholder="搜索物料名称/编码"
          style="width: 300px;"
          clearable
          @keyup.enter.native="handleProductFilter"
        />
        
        <el-button 
          type="primary" 
          @click="handleProductFilter"
          :loading="productLoading"
        >搜索</el-button>
      </div>
      
      <el-table
        :data="productList"
        border
        style="width: 100%"
        v-loading="productLoading"
        @row-click="handleProductSelect"
      >
        <el-table-column
          prop="material_code"
          label="物料编码"
          width="150"
        ></el-table-column>
        <el-table-column
          prop="material_name"
          label="物料名称"
          width="200"
        ></el-table-column>
        <el-table-column
          prop="material_sfn"
          label="规格型号"
          width="150"
        ></el-table-column>
        <el-table-column
          prop="unit"
          label="单位"
          width="80"
        ></el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleProductSizeChange"
          @current-change="handleProductPageChange"
          :current-page="productQuery.pageNum"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="productQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="productTotal"
        />
      </div>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="productDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false" :disabled="submitting">取 消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { 
  selectQcTemplateProductNameUnique, 
  insertTemplateDetail,
  updateTemplateDetail,
  fetchMaterialList
} from '@/api/qc/QualitySchemeOrder'

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    formData: {
      type: Object,
      default: () => ({
        record_id: null,
        template_id: null,
        material_id: null,
        material_code: '',
        material_name: '',
        material_sfn: '',
        unit: '',
        quantity_check_num: 1,
        quantity_unqualified_num: 0,
        cr_rate: 0,
        maj_rate: 0,
        min_rate: 100,
        remark: ''
      })
    },
    isEditMode: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      autoGenerateCode: false,
      submitting: false,
      // 防抖定时器
      _validationTimer: null,
      // 产品选择相关数据
      productDialogVisible: false,
      productList: [],
      productLoading: false,
      productTotal: 0,
      productQuery: {
        pageNum: 1,
        pageSize: 10,
        keyword: ''
      },
      localFormData: JSON.parse(JSON.stringify(this.formData)),
      rules: {
        material_code: [
          { required: true, message: '请选择物料编码', trigger: 'blur' }
        ],
        material_name: [
          { required: true, message: '请输入物料名称', trigger: 'blur' },
          { validator: this.validateNameUnique, trigger: 'blur' }
        ],
        quantity_check_num: [
          { required: true, message: '请输入最低检测数', trigger: 'blur' }
        ],
        quantity_unqualified_num: [
          { required: true, message: '请输入最大不合格数', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    formData: {
      deep: true,
      handler(newVal) {
        console.log('MaterialForm - 接收到新的formData:', newVal);
        console.log('MaterialForm - template_id:', newVal.template_id);
        this.localFormData = JSON.parse(JSON.stringify(newVal))
      }
    },
    visible: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          // 对话框打开时重置状态
          this.submitting = false
        }
      }
    }
  },
  computed: {
    dialogTitle() {
      return this.isEditMode ? '修改物料' : '添加物料'
    },
    dialogVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  beforeDestroy() {
    // 组件销毁时清理定时器
    if (this._validationTimer) {
      clearTimeout(this._validationTimer)
      this._validationTimer = null
    }
  },
  created() {
    console.log('MaterialForm组件created - props:', {
      formData: this.formData,
      template_id: this.formData.template_id,
      isEditMode: this.isEditMode
    });
    console.log('MaterialForm组件created - localFormData:', this.localFormData);
  },
  methods: {
    handleAutoGenerateChange(val) {
      console.log('自动生成编号开关状态:', val)
      if (val) {
        this.localFormData.material_code = 'MAT-' + Date.now().toString().slice(-6)
      } else {
        this.localFormData.material_code = ''
      }
    },
    
    // 检查名称唯一性
    async checkNameUnique() {
      try {
        if (!this.localFormData.material_name) {
          return;
        }
        
        // 打印template_id的值用于调试
        console.log('checkNameUnique - template_id:', this.localFormData.template_id);
        
        // 检查template_id是否存在，如果不存在则给出警告
        if (!this.localFormData.template_id) {
          console.warn('检查名称唯一性：template_id为空');
          this.$message.warning('检测方案ID为空，无法检查名称唯一性');
          return;
        }
        
        // 确保参数不为null或undefined，且template_id是数值
        const safeMaterialName = this.localFormData.material_name || '';
        // 确保template_id是数值，如果为空则使用0
        const safeTemplateId = this.localFormData.template_id || 0;
        
        console.log('执行名称唯一性检查，参数:', {
          material_name: safeMaterialName,
          template_id: safeTemplateId
        });
        
        const res = await selectQcTemplateProductNameUnique(safeMaterialName, safeTemplateId)
        
        console.log('名称唯一性检查结果:', res);
        
        // 只有明确返回false时才提示不唯一
        if (res === false) {
          this.$message.warning('该物料名称已存在，请修改')
        } else {
          // 可以考虑添加成功提示
          // this.$message.success('名称可用');
        }
      } catch (error) {
        // 详细记录错误，帮助调试
        console.error('检查名称唯一性失败详情:', {
          error,
          material_name: this.localFormData.material_name,
          template_id: this.localFormData.template_id
        });
        
        // 如果是重复提交错误，静默处理
        if (error.message && error.message.includes('重复提交')) {
          console.warn('忽略重复提交错误，继续操作');
          // 不显示任何消息
        } else {
          console.warn('检查失败但继续操作，错误:', error.message);
          // 错误消息可选
          // this.$message.warning('检查名称唯一性时发生错误，请稍后再试');
        }
      }
    },
    
    // 验证名称唯一性
    validateNameUnique(rule, value, callback) {
      if (!value) {
        callback(new Error('请输入物料名称'))
        return
      }
      
      // 打印template_id的值用于调试
      console.log('validateNameUnique - template_id:', this.localFormData.template_id);
      
      // 在编辑模式下，如果名称没有修改，跳过验证
      if (this.isEditMode && this.formData.material_name === value) {
        callback()
        return
      }
      
      // 检查template_id是否存在
      if (!this.localFormData.template_id) {
        console.warn('验证名称唯一性：template_id为空');
        // 允许表单继续提交，避免阻塞用户操作
        callback()
        return
      }
      
      // 添加防抖机制
      if (this._validationTimer) {
        clearTimeout(this._validationTimer)
      }
      
      this._validationTimer = setTimeout(() => {
        // 确保参数不为null或undefined
        const safeMaterialName = value || '';
        // 确保template_id是数值，如果为空则使用0
        const safeTemplateId = this.localFormData.template_id || 0;
        
        console.log('准备发送唯一性验证请求，参数:', {
          material_name: safeMaterialName,
          template_id: safeTemplateId
        });
        
        selectQcTemplateProductNameUnique(safeMaterialName, safeTemplateId)
          .then(res => {
            console.log('唯一性验证API响应:', res);
            
            // 只有当返回值明确是false时才提示错误
            if (res === false) {
              callback(new Error('该物料名称已存在'))
            } else {
              // 其他所有情况都通过验证
            callback()
          }
          })
          .catch((error) => {
            // 详细记录错误，帮助调试
            console.error('验证名称唯一性失败详情:', {
              error,
              material_name: safeMaterialName,
              template_id: safeTemplateId
            });
            
          // 如果是重复提交错误，静默处理
          if (error.message && error.message.includes('重复提交')) {
              console.warn('忽略重复提交错误，视为验证通过');
            callback()
          } else {
            // 其他错误记录日志但允许通过
              console.warn('验证出错但允许继续，错误:', error.message);
            callback()
          }
        })
      }, 300)
    },
    
    // 显示产品选择对话框
    showProductDialog() {
      this.productDialogVisible = true
      // 添加防抖，避免重复调用
      if (!this.productLoading) {
        this.getProductList()
      }
    },
    
    // 获取产品列表 - 使用实际的物料列表API
    async getProductList() {
      try {
        this.productLoading = true
        // 调用实际的物料列表API
        const data = {
          pageNum: this.productQuery.pageNum,
          pageSize: this.productQuery.pageSize,
          keyword: this.productQuery.keyword
        }
        
        console.log('发送物料列表请求，参数:', data);
        const response = await fetchMaterialList(data)
        
        if (response) {
          this.productList = response.rows || []
          this.productTotal = response.total || this.productList.length
        } else {
          throw new Error(response?.msg || '获取物料列表失败')
        }
      } catch (error) {
        // 如果是重复提交错误，完全跳过错误处理
        if (error.message && error.message.includes('重复提交')) {
          // 静默处理，不打印任何日志
          return
        }
        console.error('获取物料列表失败:', error)
        this.$message.error('获取物料列表失败: ' + error.message)
      } finally {
        this.productLoading = false
      }
    },
    
    // 处理产品选择
    handleProductSelect(row) {
      this.localFormData = {
        ...this.localFormData,
        material_id: row.material_id,
        material_code: row.material_code,
        material_name: row.material_name,
        material_sfn: row.material_sfn,
        unit: row.unit
      }
      this.productDialogVisible = false
    },
    
    // 产品搜索
    handleProductFilter() {
      this.productQuery.pageNum = 1
      this.getProductList()
    },
    
    // 分页相关方法
    handleProductSizeChange(val) {
      this.productQuery.pageSize = val
      this.getProductList()
    },
    
    handleProductPageChange(val) {
      this.productQuery.pageNum = val
      this.getProductList()
    },
    
    handleClose() {
      this.$refs.formRef.resetFields()
      this.submitting = false // 重置提交状态
      // 清除防抖定时器
      if (this._validationTimer) {
        clearTimeout(this._validationTimer)
        this._validationTimer = null
      }
      this.$emit('close')
    },
    
    async handleSubmit() {
      // 防止重复提交
      if (this.submitting) {
        this.$message.warning('数据正在处理，请勿重复提交')
        return
      }

      try {
        // 表单验证
        const valid = await this.$refs.formRef.validate()
        if (!valid) return
        
        // 检查template_id是否存在
         if (!this.localFormData.template_id) {
          this.$message.error('缺少模板ID，请确保从正确的位置打开此对话框')
          return
        }

        // 设置提交状态
        this.submitting = true
        console.log('开始提交表单...', this.localFormData);

        // 提交前验证名称唯一性（仅在名称有修改时验证）
        if (this.localFormData.material_name) {
          // 检查名称是否被修改
          const isNameChanged = this.isEditMode && 
            this.formData.material_name !== this.localFormData.material_name
          
          // 如果是新增模式，或者编辑模式下名称有修改，才进行唯一性验证
          if (!this.isEditMode || isNameChanged) {
            try {
              console.log('执行名称唯一性验证...');
              // 确保传递template_id
              const isUnique = await selectQcTemplateProductNameUnique(
                this.localFormData.material_name, 
                this.localFormData.template_id
              )
              
              console.log('名称唯一性验证结果:', isUnique);
              
              if (isUnique === false) { // 明确是false才提示
                this.$message.error('该物料名称已存在，请修改后重试')
                this.submitting = false // 重置提交状态
                return
              }
              
              // 添加小延迟，避免与唯一性检查请求过近
              await new Promise(resolve => setTimeout(resolve, 300));
            } catch (error) {
              // 记录错误但继续提交
              console.error('验证名称唯一性失败:', error)
              console.warn('将继续提交表单，由后端做最终验证')
              
              // 添加小延迟，避免与唯一性检查请求过近
              await new Promise(resolve => setTimeout(resolve, 300));
            }
          }
        }

        // 提交表单数据
        console.log('调用API保存数据...');
        let response;
        
        try {
        if (this.isEditMode) {
          response = await updateTemplateDetail(this.localFormData)
        } else {
          response = await insertTemplateDetail(this.localFormData)
        }
       
          console.log('API返回结果:', response);
          
          // 增强响应处理
          let submitSuccess = false;
          let recordId = null;
          
          // 检查各种可能的成功响应格式
          if (response === true || response === "true") {
            // 直接返回true表示成功
            submitSuccess = true;
          } else if (response && typeof response === 'object') {
            if (response.code === 200 || response.code === "200") {
              submitSuccess = true;
              recordId = response.data;
            } else if (response.data === true || response.data === "true") {
              submitSuccess = true;
            }
          } 
          
          // 如果成功了，继续处理
          if (submitSuccess) {
          // 使用后端返回的数据，确保有正确的record_id
            const updatedData = this.isEditMode ? 
              this.localFormData : 
              {...this.localFormData, record_id: recordId || this.localFormData.record_id || Date.now()};
            
            // 先发出事件，让父组件更新数据
            console.log('提交成功，发送事件...', updatedData);
            this.$emit('submit', updatedData);
            
            // 延迟显示成功消息并关闭对话框
            setTimeout(() => {
              this.$message.success(this.isEditMode ? '修改成功' : '添加成功');
              // 关闭对话框
              this.dialogVisible = false;
            }, 300);
          } else {
            // 处理错误响应
            const errorMsg = (response && response.msg) ? response.msg : '操作失败';
            throw new Error(errorMsg);
          }
        } catch (error) {
          // 检查后端日志是否显示成功插入
          const isPossiblySuccessful = error.message === '操作失败' || error.message.includes('重复提交');
          
          if (isPossiblySuccessful) {
            console.warn('检测到可能的异常情况：后端可能已成功但前端收到错误。尝试优雅处理...');
            
            // 构造一个"可能成功"的数据
            const possibleData = {...this.localFormData, record_id: this.localFormData.record_id || Date.now()};
            
            // 发送事件，假设操作可能已成功
            this.$emit('submit', possibleData);
            
            // 提示用户
            this.$message.warning('操作可能已成功，但系统返回了异常响应，请检查列表');
            
            // 延迟关闭对话框
            setTimeout(() => {
              this.dialogVisible = false;
            }, 1000);
        } else {
            throw error; // 重新抛出确定的错误
          }
        }
      } catch (error) {
        // 记录并显示错误
        console.error('提交失败:', error)
        this.$message.error(error.message || '提交失败')
      } finally {
        // 重置提交状态
        setTimeout(() => {
        this.submitting = false
        }, 500)
      }
    }
  }
}
</script>

<style scoped>
/* 紧凑表单样式 */
.compact-form {
  padding: 10px 20px;
}

/* 调整表单项间距 */
.el-form-item {
  margin-bottom: 16px;
}

/* 输入框宽度设置 */
.form-input {
  width: 100%;
}

.number-input {
  width: 100%;
}

.rate-input {
  width: 100%;
}

.remark-input {
  width: 100%;
}

/* 缺陷率行特殊样式 */
.defect-rate-row {
  margin-bottom: 10px;
}

.defect-rate-row .el-form-item {
  margin-bottom: 0;
}

/* 调整数字输入框按钮位置 */
:deep(.el-input-number__increase),
:deep(.el-input-number__decrease) {
  height: auto;
  line-height: 15px;
}

/* 对话框底部按钮居中 */
.dialog-footer {
  text-align: center;
}

/* 搜索区域样式 */
.filter-container {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

/* 产品选择表格样式 */
.product-table {
  margin-top: 15px;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .el-col {
    width: 100%;
  }
  
  .el-form-item {
    margin-bottom: 12px;
  }
  
  .filter-container {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-container .el-input {
    width: 100%;
    margin-bottom: 10px;
  }
}
</style>